<?php

namespace App\Libs\Company\SheetTemplateHandler\Aggregate;

use App\Libs\Company\SheetTemplateHandler\Aggregate\AbstractTemplate;
use App\Libs\Company\SheetTemplateHandler\Manager;
use App\Models\AggregateReport;

class BaseEmploymentByDistrict extends AbstractTemplate
{
    public $dataStartRow = 2;

    public function generateAbstract()
    {
        $this->renderHeader();
        $this->output['sheets']['sheet-01']['cellData']['0']['0'] = $this->createTitleCell("日喀则市{$this->task->year}年{$this->task->key}月\r{$this->template->name}");

        $aggregateTemplate = $this->template->reportTemplates()->wherePivot('frequency', $this->task->frequency)->first();
        $handler = Manager::createAggregateHandler($aggregateTemplate, $this->task);
        $data = $handler->getData();
        if (!$data) {
            return '';
        }

        $currRow = $this->dataStartRow;
        $currDistrict = null;
        $sn = 1;
        $aggregateRow = [];

        foreach ($data as $row) {
            if (is_null($currDistrict)) {
                $currDistrict = $row[1]['v'];
            }
            if (!empty($row[1]['v']) && $currDistrict != $row[1]['v']) {
                $this->output['sheets']['sheet-01']['cellData'][] = $aggregateRow;
                $currDistrict = $row[1]['v'];
                $aggregateRow = [];
            }
            if (empty($aggregateRow)) {
                $aggregateRow = [
                    ['v' => $sn++, 's' => 'CENTER'],
                    ['v' => str_replace('旅游局', '', $currDistrict), 's' => 'CENTER'],
                    ['v' => 0, 't' => 2],
                    ['v' => 0, 't' => 2],
                    ['v' => 0.0, 't' => 2],
                ];
            }
            $aggregateRow[2]['v'] += (int) $row[3]['v'];
            $aggregateRow[3]['v'] += (int) $row[4]['v'];
            $aggregateRow[4]['v'] = round($aggregateRow[4]['v'] + (float) $row[5]['v'], 2);
        }
        $this->output['sheets']['sheet-01']['cellData'][] = $aggregateRow;
        $this->dataEndRow = $currRow + $sn - 2;

        $this->renderFooter();
        return $this->output;
    }

    public function getData()
    {
        $aggregateReport = AggregateReport::where([
            'sheet_template_id' => $this->template->id,
            'frequency' => $this->task->frequency,
            'year' => $this->task->year,
            'key' => $this->task->key,
        ])
            ->first();
        $data = [];
        $this->dataEndRow = $this->dataStartRow;
        while (1) {
            $row = $aggregateReport->data['sheets']['sheet-01']['cellData'][$this->dataEndRow++] ?? [];
            if (!isset($row[0]['v']) || !is_numeric($row[0]['v'])) {
                break;
            }
            $data[] = $row;
        }
        $this->dataEndRow--;
        return $data;
    }
}
